package com.bestdreamer.synch.account1;

/**
 * 同步监视器锁
 */
public class Account {

    // 封装账户编号、账户余额两个 Field
    private String accountNo;
    private double balance;

    public Account(){}

    public Account(String accountNo,double balance){
        this.accountNo = accountNo;
        this.balance = balance;
    }
    public String getAccountNo() {
        return accountNo;
    }
    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    // 因为账户余额不允许随意修改，所以只为 balance 提供 getter 方法
    public double getBalance(){
        return this.balance;
    }

    /**
     * 提供一个线程安全的 draw() 方法来完成取钱操作
     */
    public synchronized void draw(double drawAmount){
        // 账户余额大于取钱数目
        if(balance >= drawAmount){
            // 吐出钞票
            System.out.println(Thread.currentThread().getName() + "取钱成功！取出钞票："+drawAmount);
            try{
                Thread.sleep(1);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            // 修改余额
            balance -= drawAmount;
            System.out.println("\t 余额为："+balance);
        }else {
            System.out.println(Thread.currentThread().getName()+"取钱失败！余额不足！");
        }
    }

    public int hashCode(){
        return accountNo.hashCode();
    }

    public boolean equals(Object obj){
        if(this == obj){
            return true;
        }
        if( obj != null && obj.getClass() ==Account.class){
            Account target = (Account)obj;
            return target.getAccountNo().equals(accountNo);
        }
        return false;
    }

}
